<?php

namespace common\models;

use common\components\OauthUserProvider;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%wechat_user}}".
 *
 * @property integer $id
 * @property string $nickname
 * @property string $openid
 * @property integer $sex
 * @property string $language
 * @property string $country
 * @property string $province
 * @property string $city
 * @property string $headimgurl
 * @property integer $subscribe
 * @property integer $subscribe_time
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property Member $member;
 */
class WechatUser extends \yii\db\ActiveRecord implements OauthUserProvider
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%wechat_user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sex', 'subscribe', 'subscribe_time', 'created_at', 'updated_at'], 'integer'],
            [['nickname', 'openid'], 'string', 'max' => 32],
            [['language', 'country', 'province', 'city'], 'string', 'max' => 10],
            [['headimgurl'], 'string', 'max' => 255],
        ];
    }
    
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ]
            ]
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'nickname' => '微信昵称',
            'openid' => 'Openid',
            'sex' => '性别',
            'language' => 'Language',
            'country' => '国家',
            'province' => '省份',
            'city' => '城市',
            'headimgurl' => '头像',
            'subscribe' => '订阅状态',
            'subscribe_time' => '订阅时间',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }
    
    /**
     * @param $mobile
     * @return User
     */
    public function getMember($mobile = '')
    {
        $model = $this->hasOne(User::className(), ['wechat_id' => 'openid'])->one() ?: ( ($mobile && User::findOne(['mobile' => $mobile])) ?: new User() );
        if( $model->primaryKey === null ){
            //新建用户处理信息
            $model->wechat_id = $this->openid;
            $model->username = $this->nickname;
            $model->sex = $this->sex;
            
        }
        return $model;
    }
    
    public function getName()
    {
        return 'wechat';
    }
    
    
    public function getReturnUrl()
    {
        return Yii::$app->session->get(Yii::$app->wechat->app->oauth->getRedirectUrl());
    }
    
    
    /**
     * 保存微信用户信息
     * @param $params
     * @return bool|WechatUser
     */
    public static function createOauth($params)
    {
        $model = self::findOne(['openid' => $params['openid']]) ?: new self();
        $model->attributes = $params;
        if( $model->validate() ){
            return $model->save() ? $model : false;
        }else{
            return false;
        }
    }
    
    public static function findByOpenid($openid)
    {
        return static::findOne(['openid' => $openid]);
    }
    
}
